package com.lzh.seatrend.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Classname HttpURLConnectionTest
 * @Description 请求相应流程
 * 1.begin
 * 2.读取初始URL
 * 3.将url转变为URL类对象 new URL(url)
 * 4.打开URL连接 URL.openConnection()
 * 5.连接设置
 * httpUrlConnection.setRequestMethod("GET");
 * httpUrlConnection.setUseCaches(true)；
 * 6.建立HttpURLConnection连接
 * httpUrlConnection.connection()
 * 7.读取网页内容(字符串流)
 * httpUrlConnection.getInputStream();
 * 8.end
 * @Date 2021/12/30 14:42
 * @Created by liuzihao
 */
public class HttpURLConnectionTest {
    public static void main(String[] args) {

        try {
            URL url = new URL("http://www.baidu.com/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setReadTimeout(5000);

            httpURLConnection.connect();
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                System.out.println("请求成功");
                //获取包含数据的输入流
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                //记录每一行读取的数据
                String data = "";
                //拼接字符串
//                StringBuffer stringBuffer = new StringBuffer();
//                while ((data = bufferedReader.readLine()) != null) {
//                    stringBuffer.append(data);
//                }
//                System.out.println(stringBuffer.toString());

                /**/
                String line = null;
                StringBuilder result = new StringBuilder();
                while ((line = bufferedReader.readLine()) != null) {
                    result.append(line + "\n");
                }
                System.out.println(result.toString());
                httpURLConnection.disconnect();
//                  textView.setText(stringBuffer.toString());
//                Message msg = Message.obtain();
//                msg.obj=stringBuffer.toString();
//                handler.sendMessage(msg);
            } else {
                System.out.println("请求失败");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
